package daniel.taotao.content.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import daniel.taotao.common.utils.JsonUtils;
import daniel.taotao.common.utils.TaotaoResult;
import daniel.taotao.content.service.ContentService;
import daniel.taotao.jedis.JedisClient;
import daniel.taotao.mapper.TbContentMapper;
import daniel.taotao.pojo.TbContent;
import daniel.taotao.pojo.TbContentExample;
import daniel.taotao.pojo.TbContentExample.Criteria;



@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${INDEX_CONTENT}")
	private String INDEX_CONTENT;
	
	@Override
	public TaotaoResult addContent(TbContent content) {
		//补全pojo的属性
		content.setCreated( new Date());
		content.setUpdated(new Date());
		//插入到内容表
		contentMapper.insert(content);
		jedisClient.hdel(INDEX_CONTENT, content.getCategoryId().toString());
		return TaotaoResult.ok();
	}

	@Override
	public List<TbContent> getContentByCId(Long cid) {
		try{
		String str = jedisClient.hget(INDEX_CONTENT, cid+"");
		if(StringUtils.isNotBlank(str)){
			List<TbContent> jsonToList = JsonUtils.jsonToList(str, TbContent.class);
			System.out.println("从缓存中获取");
			return jsonToList;
		}
		}catch (Exception e){
			e.printStackTrace();
		}
		TbContentExample ex=new TbContentExample();
		Criteria criteria = ex.createCriteria();
		criteria.andCategoryIdEqualTo(cid);
		List<TbContent> list2 = contentMapper.selectByExample(ex);
		try{
			jedisClient.hset(INDEX_CONTENT, cid+"", JsonUtils.objectToJson(list2));
		}catch(Exception e){
			e.printStackTrace();
		}
		return list2;
	}

}
